package com.android.settings.audio.peq.util;

import android.content.Context;
import android.os.Looper;
import android.widget.Toast;


public class ToastTool {
    static private Toast toast = null;
    private static long oneTime = 0;
    private static long twoTime = 0;
    private static String oldMsg;

    private static void setUiToast(Context context, String content) {
        // ToastTool.showToast(context, content);
        if (content == null || context == null) {
            return;
        }
        toast = Toast.makeText(context, content, Toast.LENGTH_SHORT);
        toast.show();
    }

    public static void setToast(Context context, String content) {
        if (Util.isUiThread()) {
            setUiToast(context, content);
        } else {
            Looper.prepare();
            setUiToast(context, content);
            Looper.loop();
        }
    }

    public static void showToast(Context context, String text) {
        try {
            if (Util.isUiThread()) {
                showUiToast(context, text);
            } else {
                Looper.prepare();
                showUiToast(context, text);
                Looper.loop();
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static void showUiToast(Context context, String text) {
        if (text == null || context == null) {
            return;
        }
        if (toast == null) {
            toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
            toast.show();
            oneTime = System.currentTimeMillis();
            oldMsg = text;
        } else {
            twoTime = System.currentTimeMillis();
            if (text.equals(oldMsg)) {
                if (twoTime - oneTime > Toast.LENGTH_SHORT) {
                    toast.setText(text);
                    toast.show();
                }
            } else {
                oldMsg = text;
                toast.setText(text);
                toast.show();
            }
        }
        oneTime = twoTime;
    }

    public static void showToast(Context context, int resId) {
        showToast(context, context.getResources().getString(resId));
    }
}
